local config = {
  restart_options = {"إعادة التشغيل", "Restart", "Redémarrer", "إعادة تشغيل"},
  fast_delay = 800
}

require "import"
import "android.graphics.Rect"
import "android.view.accessibility.AccessibilityNodeInfo"

local function performClick(node)
  if not node then return false end
  if node.isClickable() then 
    node.performAction(16) 
    return true 
  end
  local parent = node.getParent()
  if parent then return performClick(parent) end
  local rect = Rect()
  node.getBoundsInScreen(rect)
  return service.click(rect.centerX(), rect.centerY())
end

local function findAndClick(txts)
  local root = service.getRootInActiveWindow()
  if not root then return false end
  for _, txt in ipairs(txts) do
    local nodes = root.findAccessibilityNodeInfosByText(txt)
    if nodes and nodes.size() > 0 then
      for i = 0, nodes.size() - 1 do
        local node = nodes.get(i)
        if node.isVisibleToUser() then
          if performClick(node) then return true end
        end
      end
    end
  end
  return false
end

task(5, function()
  service.performGlobalAction(6)
  Thread.sleep(config.fast_delay)
  if findAndClick(config.restart_options) then
    Thread.sleep(config.fast_delay)
    findAndClick(config.restart_options)
  end
end)
